package cn.acmoj.oj.controller;

import cn.acmoj.oj.bean.Problem;
import cn.acmoj.oj.bean.Solution;
import cn.acmoj.oj.bean.User;
import cn.acmoj.oj.service.ProblemService;
import cn.acmoj.oj.service.SolutionService;
import cn.acmoj.oj.service.UserService;
import cn.acmoj.oj.util.Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class ProblemController {

    @Resource
    private ProblemService problemService;
    @Resource
    private SolutionService solutionService;
    @Resource
    private UserService userService;

    @RequestMapping(value = "problem", method = RequestMethod.GET)
    public String problem(@RequestParam(required = false, defaultValue = "-1") int pid,
                          HttpSession session,
                          HttpServletRequest request) {
        User user = (User) session.getAttribute("user");
        String admin = "N";
        if (user != null && userService.getPrivilege(user.getUser_id()).equals("administrator")) {
            admin = "";
        }
        try {
            Problem problem = problemService.get(pid, admin);
            problem.setTime_limit(problem.getTime_limit() * 1000);
            request.setAttribute("problem", problem);
            return "problem";
        } catch (Exception e) {
            return "redirect:/problemset.html";
        }
    }

    @RequestMapping(value = "api/submit/code", method = RequestMethod.POST)
    public String submit(@RequestParam int problem_id,
                         @RequestParam int lang,
                         @RequestParam(required = false, defaultValue = "-1") Integer contest_id,
                         @RequestParam(required = false, defaultValue = "-1") Integer num,
                         @RequestParam String code,
                         HttpServletRequest request,
                         HttpSession session) {
        User user = (User) session.getAttribute("user");
        Solution solution = new Solution();
        solution.setProblem_id(problem_id);
        solution.setUser_id(user.getUser_id());
        solution.setTime(0);
        solution.setMemory(0);
        solution.setLanguage(lang);
        solution.setIp(Util.getIp(request));
        if (contest_id != -1) {
            solution.setContest_id(contest_id);
            solution.setNum(num);
        }
        solution.setCode_length(code.length());
        solutionService.submit(solution, code);
        if (contest_id != -1) {
            return "redirect:/contest/status.html?cid=" + contest_id + "&pid=" + num;
        } else {
            return "redirect:/status.html?pid=" + problem_id;
        }
    }
}
